package com.shine.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.util.support.Base64;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;

import com.nostra13.universalimageloader.utils.L;
import com.shine.app.commons.Commons;
import com.shine.app.commons.UIHelper;

public class AppStart extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Context ctx = getApplicationContext();
		final View view = View.inflate(this, R.layout.start, null);
		setContentView(view);
		init();

		AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
		animation.setDuration(100);
		view.startAnimation(animation);
		animation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation arg0) {
				UIHelper.showHome(AppStart.this);
				overridePendingTransition(R.anim.slide_in_right,
						R.anim.slide_out_left);
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationStart(Animation animation) {
			}

		});

		try {
			if ((ctx.getPackageManager()
					.getPackageInfo(ctx.getPackageName(), 0).applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
				// Running in debug, don't update API_KEY
			} else {
				com.shine.app.commons.Urls.API_VALUE = getSigningKey(ctx);
			}
		} catch (NameNotFoundException e) {
			throw new IllegalStateException(e);
		}
	}

	private String getSigningKey(Context ctx) {
		Signature[] sigs;
		byte[] bytes;
		String key = "";

		try {
			sigs = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
					PackageManager.GET_SIGNATURES).signatures;
			bytes = MessageDigest.getInstance("MD5").digest(
					sigs[0].toByteArray());
			key = Base64.encodeBytes(bytes);
			// Log.d("OpenTee", "API_KEY = " + key);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block e.printStackTrace();
		}

		return key;
	}

	private void init() {
		getMyLocation();
		if (appContext.isReadDataCache(Commons.SEARCH_KEY)) {
			appContext.deleteFile(Commons.SEARCH_KEY);
		}
		if (appContext.isReadDataCache(Commons.GPS_KEY)) {
			appContext.deleteFile(Commons.GPS_KEY);
		}
		File testImageOnSdCard = new File("/mnt/sdcard", Commons.TEST_FILE_NAME);
		if (!testImageOnSdCard.exists()) {
			copyTestImageToSdCard(testImageOnSdCard);
		}
	}

	private void copyTestImageToSdCard(final File testImageOnSdCard) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					InputStream is = getAssets().open(Commons.TEST_FILE_NAME);
					FileOutputStream fos = new FileOutputStream(
							testImageOnSdCard);
					byte[] buffer = new byte[8192];
					int read;
					try {
						while ((read = is.read(buffer)) != -1) {
							fos.write(buffer, 0, read);
						}
					} finally {
						fos.flush();
						fos.close();
						is.close();
					}
				} catch (IOException e) {
					L.w("Can't copy test image onto SD card");
				}
			}
		}).start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}
}